<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '用户登录/注册',
  },
}
</route>
<template>
  <view class="login-container min-h-screen bg-gray-50">
    <wd-row>
      <wd-col :span="24">
        <view class="login-box">
          <!-- 标题 -->
          <wd-row>
            <wd-col :span="24">
              <view class="text-center py-8">
                <text class="text-2xl font-bold text-gray-800">
                  {{ isLogin ? '欢迎登录' : '用户注册' }}
                </text>
              </view>
            </wd-col>
          </wd-row>

          <!-- 切换登录/注册 -->
          <wd-row>
            <wd-col :span="24">
              <view class="flex justify-end mb-4">
                <text class="text-blue-500" @click="toggleForm">
                  {{ isLogin ? '没有账号？去注册' : '已有账号？去登录' }}
                </text>
              </view>
            </wd-col>
          </wd-row>

          <!-- 表单区域 -->
          <wd-row>
            <wd-col :span="24">
              <!-- 登录表单 -->
              <wd-form
                v-if="isLogin"
                ref="loginForm"
                :model="loginData"
                :rules="loginRules"
                errorType="message"
              >
                <wd-cell-group border>
                  <!-- 用户名输入框 -->
                  <wd-input
                    label="用户名"
                    label-width="80px"
                    prop="username"
                    v-model="loginData.username"
                    placeholder="请输入用户名"
                    clearable
                    :rules="[{ required: true, message: '请输入用户名' }]"
                  />

                  <!-- 密码输入框 -->
                  <wd-input
                    label="密码"
                    label-width="80px"
                    prop="password"
                    show-password
                    v-model="loginData.password"
                    placeholder="请输入密码"
                    clearable
                    :rules="[{ required: true, message: '请输入密码' }]"
                  />
                </wd-cell-group>
                <!-- 登录按钮 -->
                <wd-row>
                  <wd-col :span="24">
                    <view class="px-4 mt-8">
                      <wd-button type="primary" size="large" @click="handleLogin" block>
                        登录
                      </wd-button>
                    </view>
                  </wd-col>
                </wd-row>
              </wd-form>

              <!-- 注册表单 -->
              <wd-form
                v-else
                ref="registerForm"
                :model="registerData"
                :rules="registerRules"
                errorType="message"
              >
                <wd-cell-group border>
                  <!-- 用户名输入框 -->
                  <wd-input
                    label="用户名"
                    label-width="80px"
                    prop="username"
                    v-model="registerData.username"
                    placeholder="请输入用户名"
                    clearable
                    :rules="[{ required: true, message: '请输入用户名' }]"
                  />

                  <!-- 密码输入框 -->
                  <wd-input
                    label="密码"
                    label-width="80px"
                    prop="password"
                    show-password
                    v-model="registerData.password"
                    placeholder="请输入密码"
                    clearable
                    :rules="[{ required: true, message: '请输入密码' }]"
                  />

                  <!-- 手机号输入框 -->
                  <wd-input
                    label="手机号"
                    label-width="80px"
                    prop="phone"
                    v-model="registerData.phone"
                    placeholder="请输入手机号"
                    clearable
                    :rules="[{ required: true, message: '请输入手机号' }]"
                  />
                </wd-cell-group>
                <!-- 注册按钮 -->
                <wd-row>
                  <wd-col :span="24">
                    <view class="px-4 mt-8">
                      <wd-button type="primary" size="large" @click="handleRegister" block>
                        注册
                      </wd-button>
                    </view>
                  </wd-col>
                </wd-row>
              </wd-form>
            </wd-col>
          </wd-row>

          <!-- 其他登录方式 -->
          <wd-row v-if="isLogin">
            <wd-col :span="24">
              <view class="mt-12">
                <view class="text-gray-500 text-sm mb-6 text-center">其他登录方式</view>
                <view class="flex justify-center space-x-12">
                  <view class="flex flex-col items-center">
                    <view
                      class="w-12 h-12 rounded-full bg-green-50 flex items-center justify-center mb-2"
                    >
                      <text class="i-carbon-logo-wechat text-2xl text-green-600"></text>
                    </view>
                    <text class="text-sm text-gray-600">微信</text>
                  </view>
                  <view class="flex flex-col items-center">
                    <view
                      class="w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center mb-2"
                    >
                      <text class="i-carbon-phone text-2xl text-blue-600"></text>
                    </view>
                    <text class="text-sm text-gray-600">手机号</text>
                  </view>
                </view>
              </view>
            </wd-col>
          </wd-row>

          <!-- 加载中遮罩 -->
          <wd-overlay :show="loading">
            <view class="wrapper">
              <wd-loading />
            </view>
          </wd-overlay>
        </view>
      </wd-col>
    </wd-row>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useToast } from 'wot-design-uni'
import { login, register } from '@/service/auth/login'
import { useUserStore } from '@/store'
const { success: showSuccess, error: showError } = useToast()
const userStore = useUserStore()

// 是否显示登录表单
const isLogin = ref(true)

// 登录表单数据
const loginData = reactive({
  username: '',
  password: '',
})

// 注册表单数据
const registerData = reactive({
  username: '',
  password: '',
  phone: '',
})

// 登录表单规则
const loginRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      validator: (value: string) => {
        if (value && value.length >= 3) {
          return Promise.resolve()
        }
        return Promise.reject(new Error('用户名至少3个字符'))
      },
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      validator: (value: string) => {
        if (value && value.length >= 6) {
          return Promise.resolve()
        }
        return Promise.reject(new Error('密码至少6个字符'))
      },
    },
  ],
}

// 注册表单规则
const registerRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      validator: (value: string) => {
        if (value && value.length >= 3) {
          return Promise.resolve()
        }
        return Promise.reject(new Error('用户名至少3个字符'))
      },
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      validator: (value: string) => {
        if (value && value.length >= 6) {
          return Promise.resolve()
        }
        return Promise.reject(new Error('密码至少6个字符'))
      },
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号',
      validator: (value: string) => {
        if (value && /^1[3-9]\d{9}$/.test(value)) {
          return Promise.resolve()
        }
        return Promise.reject(new Error('请输入正确的手机号'))
      },
    },
  ],
}

// 登录请求
const { data: loginResponseData, loading, run: runLogin } = useRequest<any>(() => login(loginData))
const loginForm = ref()

// 注册请求
const registerForm = ref()

// 切换登录/注册表单
const toggleForm = () => {
  isLogin.value = !isLogin.value
}

// 登录处理
const handleLogin = () => {
  loginForm.value
    .validate()
    .then(async ({ valid }) => {
      if (valid) {
        await runLogin()
        if (loginResponseData.value) {
          const { token, role } = loginResponseData.value
          // 先设置token
          userStore.setToken(token)
          userStore.setRole(role)
          showSuccess('登录成功')
          // 延迟跳转，确保store更新完成
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/my/index',
            })
          }, 1000)
        }
      }
    })
    .catch((error: any) => {
      showError(error.message || '登录失败')
      return error
    })
}

// 注册处理
const handleRegister = () => {
  registerForm.value
    .validate()
    .then(async ({ valid }) => {
      if (valid) {
        const res = await register(registerData).catch()
        // console.log('注册结果:', res)
        if (res.code === 200) {
          showSuccess('注册成功')
          // 注册成功后切换到登录表单
          isLogin.value = true
          // 将注册的用户名和密码填入登录表单
          loginData.username = registerData.username
          loginData.password = registerData.password
        }
      }
    })
    .catch((error: any) => {
      showError(error.message || '注册失败')
      return error
    })
}
</script>

<style lang="scss" scoped>
.login-container {
  background-color: #fff;
}

.login-box {
  min-height: 100vh;
  padding: 0 32rpx;
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: 120px;
  height: 120px;
  background-color: #fff;
}
</style>
